package com.dragon.modules.yuegou.service.impl.busd;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.busd.DistrictEntity;
import com.dragon.modules.yuegou.entity.busd.OperationDataEntity;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.dragon.modules.yuegou.mapper.busd.OperationDataMapper;
import com.dragon.modules.yuegou.model.busd.OperationData;
import com.dragon.modules.yuegou.query.busd.OperationDataQuery;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.busd.OperationDataService;
import com.dragon.modules.yuegou.web.Check;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.YearMonth;
import java.util.List;

/**
 * 商圈运营数据表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-12-27 10:02:45
 * @version 2.0
 */
@Service("busdOperationDataService")
public class OperationDataServiceImpl
		extends ServiceImpl<OperationDataMapper, OperationDataEntity>
		implements OperationDataService {

	@Autowired
	private DistrictService districtService;
	
	@Override
	public void saveData(OperationData operationData) {
		Check.notNull(operationData.getCustomerFlow(), "客流量不能为空");
		Check.notNull(operationData.getOpenRate(), "开门营业率不能为空");
		Check.digits(operationData.getOpenRate(), 10, 4, "开门营业率最多保留四位小数");
		
		if (YearMonth.parse(operationData.getMonth()).isAfter(YearMonth.now())) {
			throw new DragonException(SystemCode.YEAR_MONTH_AFTER);
		}
		
		OperationDataQuery query = new OperationDataQuery();
		query.setBusdId(operationData.getBusdId());
		query.setMonth(operationData.getMonth());
		List<OperationDataEntity> dataList = baseMapper.selectList(query.toQueryWrapper());
		if (CollectionUtils.isEmpty(dataList)) {
			DistrictEntity district = districtService.getById(operationData.getBusdId());
			operationData.setBusdName(district.getBcName());
			baseMapper.insert(operationData);
		}else {
			OperationDataEntity data = dataList.get(0);
			data.setOpenRate(operationData.getOpenRate());
			data.setCustomerFlow(operationData.getCustomerFlow());
			baseMapper.updateById(data);
		}
	}

}